package com.ruoyi.product.service.impl;

import com.ruoyi.common.utils.SpecGroupUtils;
import com.ruoyi.product.domain.ProductSpu;
import com.ruoyi.product.domain.ProductSpuDto;
import com.ruoyi.product.domain.dto.ProductDetailDto;
import com.ruoyi.product.domain.vo.Activity;
import com.ruoyi.product.domain.vo.Coupon;
import com.ruoyi.product.domain.vo.Sku;
import com.ruoyi.product.mapper.ProductSpuMapper;
import com.ruoyi.product.service.IProductSpuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 商品SPUService业务层处理
 *
 * @author liuhuizhong
 * @date 2025-08-07
 */
@Service
public class ProductSpuServiceImpl implements IProductSpuService {
    @Autowired
    private ProductSpuMapper productSpuMapper;

    /**
     * 查询商品SPU
     *
     * @param id 商品SPU主键
     * @return 商品SPU
     */
    @Override
    public ProductSpu selectProductSpuById(Long id) {
        return productSpuMapper.selectProductSpuById(id);
    }

    /**
     * 查询商品SPU列表
     *
     * @param productSpuDto 商品SPU
     * @return 商品SPU
     */
    @Override
    public List<ProductSpuDto> selectProductSpuList(ProductSpuDto productSpuDto) {
        List<ProductSpuDto> rawList = productSpuMapper.selectProductSpuList(productSpuDto);

        Map<String, ProductSpuDto> mergedMap = new LinkedHashMap<>();
        for (ProductSpuDto item : rawList) {
            String key = buildMergeKey(item);

            ProductSpuDto existing = mergedMap.get(key);
            if (existing == null) {
                ProductSpuDto copy = new ProductSpuDto();
                copy.setId(item.getId());
                copy.setName(item.getName());
                copy.setSubTitle(item.getSubTitle());
                copy.setDescription(item.getDescription());
                copy.setCostPrice(item.getCostPrice());
                copy.setStock(item.getStock());
                copy.setWeight(item.getWeight());
                copy.setVolume(item.getVolume());
                copy.setSpecNameGroup(SpecGroupUtils.processSpecNameGroup(item.getSpecNameGroupRaw()));
                copy.setSpecValueGroup(SpecGroupUtils.processSpecValueGroup(item.getSpecValueGroupRaw()));
                copy.setPrice(item.getPrice());
                copy.setOriginalPrice(item.getOriginalPrice());
                copy.setUrl(item.getUrl());
                copy.setUrls(new ArrayList<>());

                // 封装urls[]
                if (item.getUrl() != null && !item.getUrl().isEmpty()) {
                    copy.getUrls().add(item.getUrl());
                }
                mergedMap.put(key, copy);
            } else {
                if (item.getUrl() != null && !item.getUrl().isEmpty()) {
                    List<String> urls = existing.getUrls();
                    if (urls == null) {
                        urls = new ArrayList<>();
                        existing.setUrls(urls);
                    }
                    if (!urls.contains(item.getUrl())) {
                        urls.add(item.getUrl());
                    }
                }
            }

        }
        return new ArrayList<>(mergedMap.values());
    }

    public String buildMergeKey(ProductSpuDto item) {
        Long id = item.getId();
        BigDecimal price = item.getPrice();
        BigDecimal originalPrice = item.getOriginalPrice();
        return (id == null ? "" : String.valueOf(id)) + "|" +
                (price == null ? "" : String.valueOf(price)) + "|" +
                (originalPrice == null ? "" : String.valueOf(originalPrice));
    }

    /**
     * 新增商品SPU
     *
     * @param productSpu 商品SPU
     * @return 结果
     */
    @Override
    public int insertProductSpu(ProductSpu productSpu) {
        return productSpuMapper.insertProductSpu(productSpu);
    }

    /**
     * 修改商品SPU
     *
     * @param productSpu 商品SPU
     * @return 结果
     */
    @Override
    public int updateProductSpu(ProductSpu productSpu) {
        return productSpuMapper.updateProductSpu(productSpu);
    }

    /**
     * 批量删除商品SPU
     *
     * @param ids 需要删除的商品SPU主键
     * @return 结果
     */
    @Override
    public int deleteProductSpuByIds(Long[] ids) {
        return productSpuMapper.deleteProductSpuByIds(ids);
    }

    /**
     * 删除商品SPU信息
     *
     * @param id 商品SPU主键
     * @return 结果
     */
    @Override
    public int deleteProductSpuById(Long id) {
        return productSpuMapper.deleteProductSpuById(id);
    }

    /**
     * 查询商品详情
     *
     * @param id 商品ID
     * @return 商品详情
     */
    @Override
    public ProductDetailDto selectProductSpuDetail(Long id) {
        List<ProductDetailDto> mapList = productSpuMapper.selectProductSpuDetail(id);
        if (mapList == null || mapList.isEmpty()) {
            return null;
        }

        // 创建主DTO对象
        ProductDetailDto dto = new ProductDetailDto();
        dto.setSpuId(mapList.get(0).getSpuId());
        dto.setSpuName(mapList.get(0).getSpuName());
        dto.setSpuTitle(mapList.get(0).getSpuTitle());
        dto.setSpuDescription(mapList.get(0).getSpuDescription());

        // 用于存储SKU、活动和优惠券的Map
        Map<Long, Sku> skuMap = new LinkedHashMap<>();
        Map<Long, Activity> activityMap = new LinkedHashMap<>();
        Map<Long, Coupon> couponMap = new LinkedHashMap<>();

        // 第一遍遍历：构建SKU、Activity和Coupon对象
        for (ProductDetailDto item : mapList) {
            if (item.getSpuId() == null) {
                continue;
            }

            // 处理SKU
            if (item.getSkuId() != null) {
                Sku sku = skuMap.get(item.getSkuId());
                if (sku == null) {
                    sku = new Sku();
                    sku.setSkuId(item.getSkuId());
                    sku.setSpuId(item.getSpuId());
                    sku.setCode(item.getCode());
                    sku.setCategoryId(item.getCategoryId());
                    sku.setSpecData(item.getSpecData());
                    sku.setPrice(item.getPrice());
                    sku.setOriginalPrice(item.getOriginalPrice());
                    sku.setStock(item.getStock());
                    sku.setLowStock(item.getLowStock());
                    sku.setWeight(item.getWeight());
                    sku.setVolume(item.getVolume());
                    sku.setStatus(item.getStatus());
                    sku.setSpecNameGroup(SpecGroupUtils.processSpecNameGroup(item.getSpecNameGroupRaw()));
                    sku.setSpecValueGroup(SpecGroupUtils.processSpecValueGroup(item.getSpecValueGroupRaw()));
                    sku.setCreatedAt(item.getCreatedAt());
                    sku.setUpdatedAt(item.getUpdatedAt());
                    sku.setUrl(item.getUrl());
                    sku.setSkuName(item.getSkuName());
                    sku.setUrls(new ArrayList<>());
                    sku.setActivityList(new ArrayList<>());
                    sku.setCouponList(new ArrayList<>());
                    skuMap.put(item.getSkuId(), sku);
                }

                // 处理图片URLs
                if (item.getUrl() != null && !item.getUrl().isEmpty() && !sku.getUrls().contains(item.getUrl())) {
                    sku.getUrls().add(item.getUrl());
                }
            }

            // 处理Activity
            if (item.getActivityId() != null) {
                Long activityId = item.getActivityId();
                Activity activity = activityMap.get(activityId);
                if (activity == null) {
                    activity = new Activity();
                    activity.setActivityId(item.getActivityId());
                    activity.setActivityName(item.getActivityName());
                    activity.setActivityType(item.getActivityType());
                    activity.setActivityDescription(item.getActivityDescription());
                    activity.setActivityStatus(item.getActivityStatus());
                    activity.setActivityEndTime(item.getActivityEndTime());
                    activity.setActivityCreateTime(item.getActivityCreateTime());
                    activityMap.put(activityId, activity);
                }
            }

            // 处理Coupon
            if (item.getCouponId() != null) {
                Long couponId = item.getCouponId();
                Coupon coupon = couponMap.get(couponId);
                if (coupon == null) {
                    coupon = new Coupon();
                    coupon.setCouponId(item.getCouponId());
                    coupon.setCouponCode(item.getCouponCode());
                    coupon.setCouponType(item.getCouponType());
                    coupon.setCouponValue(item.getCouponValue());
                    coupon.setCouponMinAmount(item.getCouponMinAmount());
                    coupon.setCouponStartTime(item.getCouponStartTime());
                    coupon.setCouponEndTime(item.getCouponEndTime());
                    couponMap.put(couponId, coupon);
                }
            }
        }

        // 第二遍遍历：建立SKU与Activity、Coupon的关联关系
        for (ProductDetailDto item : mapList) {
            if (item.getSkuId() != null) {
                Sku sku = skuMap.get(item.getSkuId());
                if (sku != null) {
                    // 关联Activity
                    if (item.getActivityId() != null) {
                        Activity activity = activityMap.get(item.getActivityId());
                        if (activity != null && !sku.getActivityList().contains(activity)) {
                            sku.getActivityList().add(activity);
                        }
                    }

                    // 关联Coupon
                    if (item.getCouponId() != null) {
                        Coupon coupon = couponMap.get(item.getCouponId());
                        if (coupon != null && !sku.getCouponList().contains(coupon)) {
                            sku.getCouponList().add(coupon);
                        }
                    }
                }
            }
        }

        // 设置SKU列表到主DTO
        dto.setSkus(new ArrayList<>(skuMap.values()));

        return dto;
    }

}
